<template>
  <div>
    <input type="file" @change="handleFileChange">
    <button @click="uploadChunkFile" :disabled="!selectedFile">分片上传文件</button>
    <div v-if="uploading">
      <div>上传进度: {{ uploadProgress }}%</div>
      <div class="progress-bar">
        <div class="progress" :style="{ width: uploadProgress + '%' }"></div>
      </div>
    </div>
    <div v-if="uploaded">上传完成</div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      selectedFile: null,
      uploadProgress: 0,
      uploading: false,
      uploaded: false,
      uploadId: null, // 新增：记录上传ID
      uploadedChunks: [] // 新增：已上传分片索引列表
    };
  },
  methods: {
    handleFileChange(event) {
      this.selectedFile = event.target.files[0];
    },
    async uploadChunkFile() {
      if (!this.selectedFile) return;
      const chunkSize = 1024 * 1024;
      const totalChunks = Math.ceil(this.selectedFile.size / chunkSize);
      this.uploadProgress = 0;
      this.uploading = true;
      this.uploaded = false;

      // 生成或复用uploadId
      if (!this.uploadId) {
        this.uploadId = Date.now().toString();
      }
      // 获取已上传分片列表
      try {
        const response = await axios.get('http://localhost:3000/upload/chunks', {
          params: {
            uploadId: this.uploadId,
            fileName: this.selectedFile.name
          }
        });
        this.uploadedChunks = response.data.uploadedIndices || [];
      } catch (error) {
        console.error('获取已上传分片失败:', error);
        return;
      }

      let uploadedCount = this.uploadedChunks.length;
      const total = totalChunks;

      // 跳过已上传分片
      for (let i = 0; i < totalChunks; i++) {
        if (this.uploadedChunks.includes(i)) continue;

        const start = i * chunkSize;
        const end = Math.min(start + chunkSize, this.selectedFile.size);
        const chunk = this.selectedFile.slice(start, end);

        const formData = new FormData();
        formData.append('file', chunk);
        formData.append('index', i);
        formData.append('uploadId', this.uploadId);
        formData.append('fileName', this.selectedFile.name);

        try {
          await axios.post('http://localhost:3000/upload/chunk', formData);
          uploadedCount++;
          this.uploadedChunks.push(i);
          this.uploadProgress = (uploadedCount / total) * 100;
        } catch (error) {
          console.error(`分片 ${i} 上传失败:`, error);
          // 继续后续分片上传
        }
      }

      // 所有分片上传完成后再合并
      if (uploadedCount === totalChunks) {
        try {
          const formDataMerge = new FormData();
          formDataMerge.append('uploadId', this.uploadId);
          formDataMerge.append('fileName', this.selectedFile.name);
          await axios.post('http://localhost:3000/upload/merge', formDataMerge);
          this.uploading = false;
          this.uploaded = true;
        } catch (error) {
          console.error('合并分片失败:', error);
        }
      } else {
        console.error('部分分片未上传成功，无法合并');
      }
    }
  }
};
</script>

<style scoped>
.progress-bar {
  width: 100%;
  background-color: #f3f3f3;
  border-radius: 5px;
  overflow: hidden;
}

.progress {
  height: 20px;
  background-color: #4caf50;
  text-align: center;
  line-height: 20px;
  color: white;
}
</style>    